package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.entity.RolePers;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RoleMapper;
import cn.kgc.vue.mapper.RolePersMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import cn.kgc.vue.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mengshun
 * @description 针对表【sys_role】的数据库操作Service实现
 * @createDate 2024-07-03 14:20:13
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePersMapper rolePersMapper;

    @Resource
    private PermissionMapper permissionMapper;


    @Override
    public ResponseResult rolePage(QueryCondition<Role> params) {

        Page<Role> rolePage = new Page<>(params.getPage(), params.getLimit());
        Role searchParams = params.getSearchParams();
        String roleEn = searchParams.getRoleEn();
        String roleCh = searchParams.getRoleCh();

        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.like(StringUtils.isNotBlank(roleCh), Role::getRoleCh, roleCh)
                .like(StringUtils.isNotBlank(roleEn), Role::getRoleEn, roleEn);

        baseMapper.selectPage(rolePage, lambda);

        return ResponseResult.success().data("total", rolePage.getTotal()).data("tableData", rolePage.getRecords());
    }

    @Transactional
    @Override
    public ResponseResult delete(Integer id) {

        // 1.判定删除的角色  是否被占用  rid  user_role
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId, id);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (ObjectUtils.isNotNull(userRoles)) {
            return ResponseResult.fail().message("角色被占用,不能删除");
        }

        // 2. 角色没有被占用 则删除角色
        baseMapper.deleteById(id);

        // 3. 删除角色和权限的关联数据 role_permission
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getRoleId, id);
        rolePersMapper.delete(lambda1);

        return ResponseResult.success().message("删除成功");
    }

    @Override
    public ResponseResult rolePermissions(Integer rid) {

        // 1. role_permission    pid
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId, rid);

        List<Integer> pids = rolePersMapper.selectList(lambda).stream().map(rp -> rp.getPerId())
                .collect(Collectors.toList());


        LambdaQueryWrapper<Permission> permissionLambda = new QueryWrapper<Permission>().lambda();
        permissionLambda.eq(Permission::getIsMenu, 2)
                .in(Permission::getId, pids);


        List<Integer> defaultKeys = permissionMapper.selectList(permissionLambda).stream()
                .map(p -> p.getId())
                .collect(Collectors.toList());

        return ResponseResult.success().data("defaultKeys", defaultKeys);
    }

    @Transactional
    @Override
    public ResponseResult editRolePermissions(HashMap<String, Object> params) {

        Integer rid = (Integer) params.get("rid");
        log.debug("rid={}",rid);

        List<Integer> pIds = (List<Integer>) params.get("newKeys");
        log.debug("pIds={}",pIds);


        // 1.删除角色权限
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,rid);
        rolePersMapper.delete(lambda);

        // 2. 添加角色最新权限
        pIds.forEach(pid->{
            RolePers rolePers = new RolePers();
            rolePers.setPerId(pid);
            rolePers.setRoleId(rid);
            rolePersMapper.insert(rolePers);
        });
        return ResponseResult.success().message("权限分配成功");
    }
}




